﻿#include "Heap.h"

//初始化
void HPInit(HP* php)
{
	assert(php);
	php->arr = NULL;
	php->size = php->capacity = 0;
}

//销毁
void HPDestroy(HP* php)
{
	assert(php);
	if (php->arr)
	{
		free(php->arr);
	}
	php->arr = NULL;
	php->capacity = php->size = 0;
}

void Swap(int* x, int* y)
{
	int temp = *x;
	*x = *y;
	*y = temp;
}

//向上调整算法
void AdjustUp(HPDataType* a, int child)
{
	assert(a);
	int parent = (child - 1) / 2;
	while (child>0)
	{
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

//堆的插⼊
void HPPush(HP* php, HPDataType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		 int newcapacity = php->capacity == 0 ? 4 : 2 * php->capacity;
		 HPDataType* temp=(HPDataType*)realloc(php->arr, sizeof(HPDataType) * newcapacity);
		 if (temp == NULL)
		 {
			 perror("realloc fail!\n");
			 exit(1);
		 }
		php->arr = temp;
		php->capacity = newcapacity;
	}
	php->arr[php->size] = x;
	AdjustUp(php->arr, php->size);
	php->size++;
}

// 判空
bool HPEmpty(HP* php)
{
	assert(php);
	return php->size == 0;
}
//求size
int HPSize(HP* php)
{
	assert(php);
	return php->size;
}

//向下调整算法
void AdjustDown(HPDataType* a, int n, int parent)
{
	assert(a);
	int child = parent * 2 + 1;
	while (child<n)
	{
		if (child+1 < n && a[child] > a[child + 1])//先找孩子结点
		{
			child++;
		}
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

//堆的删除
void HPPop(HP* php)
{
	assert(php);
	assert(!HPEmpty(php));
	Swap(&php->arr[0], &php->arr[php->size-1]);
	php->size--;
	AdjustDown(php->arr, php->size, 0);
}